package com.example.uploadfile.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author:ChenSheng
 * @Description:
 * @Date: Created in 下午 15:39 2018/6/13 0013
 */
@Controller
public class FileController {

    @PostMapping("/uploadFile")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        //String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        String filePath = request.getSession().getServletContext().getRealPath("images/");
        String result = storeFile(file.getBytes(), filePath, fileName);

        /*FileOutputStream out = new FileOutputStream("d:/images/a.png");
        out.write(file.getBytes());
        out.flush();
        out.close();*/

        return result;
    }

    @RequestMapping("/home")
    public String home(){
        return "home";
    }

    private String storeFile(byte[] file, String filePath, String fileName) throws IOException{
        File targetFilePath = new File(filePath);
        if(!targetFilePath.exists()){
            targetFilePath.mkdir();
        }
        String result = filePath + fileName;
        FileOutputStream out = new FileOutputStream(result);
        out.write(file);
        out.flush();
        out.close();
        return result;
    }

}
